<?php

class Wall_IndexController extends Core_Controller_Action_Standard
{

	public function postAction()
	{
		// Make sure user exists
		if (!$this->_helper->requireUser()->isValid())
			return;

		// Get subject if necessary
		$viewer = Engine_Api::_()->user()->getViewer();
		$subject = null;
		$subject_guid = $this->_getParam('subject', null);
		if ($subject_guid)
		{
			$subject = Engine_Api::_()->getItemByGuid($subject_guid);
		}
		// Use viewer as subject if no subject
		if (null === $subject)
		{
			$subject = $viewer;
		}

		// Make form
		$form = $this->view->form = new Wall_Form_Post();

		// Check auth
		if (!$subject->authorization()->isAllowed($viewer, 'comment'))
		{
			return $this->_helper->requireAuth()->forward();
		}

		// Check if post
		if (!$this->getRequest()->isPost())
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Not post');
			return;
		}

		// Check if form is valid
		$postData = $this->getRequest()->getPost();

		// var_dump($postData);
		// exit;
		/* $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
		  $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
		  //$body = htmlentities($body, ENT_QUOTES, 'UTF-8'); */

		$body = $postData['body'];
		if (isset($postData['body_html']) && $postData['body_html'] != '')
		{
			$body = $postData['body_html'];
		}
		$postData['body'] = $body;


		if (!$form->isValid($postData))
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid data');
			return;
		}

		// Check one more thing
		if ($form->body->getValue() === '' && $form->getValue('attachment_type') === '')
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid data');
			return;
		}


		// Process
		$db = Engine_Api::_()->getDbtable('actions', 'activity')->getAdapter();
		$db->beginTransaction();

		try
		{
			// Try attachment getting stuff
			$attachment = null;
			$attachmentData = $this->getRequest()->getParam('attachment');
			if (!empty($attachmentData) && !empty($attachmentData['type']))
			{
				$type = $attachmentData['type'];
				$config = null;
				foreach (Zend_Registry::get('Engine_Manifest') as $data)
				{
					if (!empty($data['composer'][$type]))
					{
						$config = $data['composer'][$type];
					}
				}
				if (!empty($config['auth']) && !Engine_Api::_()->authorization()->isAllowed($config['auth'][0], null, $config['auth'][1]))
				{
					$config = null;
				}
				if ($config)
				{
					$plugin = Engine_Api::_()->loadClass($config['plugin']);
					$method = 'onAttach' . ucfirst($type);
					$attachment = $plugin->$method($attachmentData);
				}
			}

			// var_dump($postData);
			// exit;
			// Get body
			//$body = $form->getValue('body');          
			$body = preg_replace('/<br[^<>]*>/', "\n", $body);
			$body = str_replace('../', '', $body);
			$body = strip_tags($body, '<a>');
//          $body = preg_replace('@((https?://)?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $body);
//          $body = preg_replace('/href="www/', 'href="http://www', $body);
			//$body = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1">$1</a>', $body);
			//echo $body;
			//die();
			// Is double encoded because of design mode
			//$body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
			//$body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
			//$body = htmlentities($body, ENT_QUOTES, 'UTF-8');
			// Special case: status
			if (!$attachment && $viewer->isSelf($subject))
			{
				if ($body != '')
				{
					$viewer->status = $body;
					$viewer->status_date = date('Y-m-d H:i:s');
					$viewer->save();

					$viewer->status()->setStatus($body);
				}

				$action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $subject, 'status', $body);
			}

			// General post
			else
			{
				$type = 'post';
				if ($viewer->isSelf($subject))
				{
					$type = 'post_self';
				}


				$subjectOwner = $subject->getOwner();

				if (!$viewer->isSelf($subject) && $subject instanceof User_Model_User)
				{
					$notificationType = 'post_' . $subject->getType();
					Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($subjectOwner, $viewer, $subject, $notificationType, array(
						'url1' => $subject->getHref(),
					));
				}

				if (!$viewer->isSelf($subject))
				{
					//if( $subject instanceof User_Model_User )
				}

				// Add activity
				$action = $this->_helper->api()->getDbtable('actions', 'activity')->addActivity($viewer, $subject, $type, $body);

				// Try to attach if necessary
				if ($action && $attachment)
				{
					$this->_helper->api()->getDbtable('actions', 'activity')->attachActivity($action, $attachment);
				}
			}

			// Publish to facebook, if checked & enabled
			if ($this->_getParam('post_to_facebook', false) &&
					'publish' == Engine_Api::_()->getApi('settings', 'core')->core_facebook_enable)
			{
				try
				{

					$facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
					$facebook = $facebookApi = $facebookTable->getApi();
					$fb_uid = $facebookTable->find($viewer->getIdentity())->current();

					if ($fb_uid &&
							$fb_uid->facebook_uid &&
							$facebookApi &&
							$facebookApi->getUser() &&
							$facebookApi->getUser() == $fb_uid->facebook_uid)
					{
						$url = 'http://' . $_SERVER['HTTP_HOST'] . $this->getFrontController()->getBaseUrl();
						$name = 'Activity Feed';
						$desc = '';
						$picUrl = $viewer->getPhotoUrl('thumb.icon');
						if ($attachment)
						{
							$url = $attachment->getHref();
							$desc = $attachment->getDescription();
							$name = $attachment->getTitle();
							if (empty($name))
							{
								$name = ucwords($attachment->getShortType());
							}
							$tmpPicUrl = $attachment->getPhotoUrl();
							if ($tmpPicUrl)
							{
								$picUrl = $tmpPicUrl;
							}
							// prevents OAuthException: (#100) FBCDN image is not allowed in stream
							if (preg_match('/fbcdn.net$/i', parse_url($picUrl, PHP_URL_HOST)))
							{
								$picUrl = $viewer->getPhotoUrl('thumb.icon');
							}
						}

						// Check stuff
						if (false === stripos($url, 'http://'))
						{
							$url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
						}
						if (false === stripos($picUrl, 'http://'))
						{
							$picUrl = 'http://' . $_SERVER['HTTP_HOST'] . $picUrl;
						}

						// include the site name with the post:
						$name = Engine_Api::_()->getApi('settings', 'core')->core_general_site_title
								. ": $name";

						$fb_data = array(
							'message' => html_entity_decode($form->getValue('body')),
							'link' => $url,
							'name' => $name,
							'description' => $desc,
						);

						if ($picUrl)
						{
							$fb_data = array_merge($fb_data, array('picture' => $picUrl));
						}

						$res = $facebookApi->api('/me/feed', 'POST', $fb_data);
					}
				}
				catch (Exception $e)
				{
					// Silence
				}
			} // end Facebook
			// Publish to twitter, if checked & enabled
			if ($this->_getParam('post_to_twitter', false) &&
					'publish' == Engine_Api::_()->getApi('settings', 'core')->core_twitter_enable)
			{
				try
				{
					$twitterTable = Engine_Api::_()->getDbtable('twitter', 'user');
					if ($twitterTable->isConnected())
					{
						// @todo truncation?
						// @todo attachment
						$twitter = $twitterTable->getApi();
						$twitter->statuses->update(html_entity_decode($form->getValue('body')));
					}
				}
				catch (Exception $e)
				{
					// Silence
				}
			} // end Facebook

			/**
			 * Set Privacy if neccessary
			 */
			$privacy_set = $this->getRequest()->getParam('privacy');
			if ($privacy_set)
			{
				$privacy = $this->_helper->api()->getDbtable('privacies', 'wall');
				$row = $privacy->createRow();
				$row->action_id = $action->action_id;
				$row->user_id = $viewer->user_id;
				$row->privacy = $privacy_set;
				$row->save();
			}
			/**
			 * Tags Friend
			 */
			$viewer = $this->_helper->api()->user()->getViewer();

			//$action_id = $this->view->action_id = $this->_getParam('action_id', $this->_getParam('action', null));
			//$action = $this->_helper->api()->getDbtable('actions', 'activity')->getActionById($action_id);

			$tags = array();
			$friendusers = array();

			if (isset($postData['tagged_users']) && $postData['tagged_users'])
			{
				foreach (explode(',', $postData['tagged_users']) as $tag)
				{
					$tags[] = $t = split(';', $tag);
					$friendusers[] = $t[1];
				}
			}

			if ($friendusers)
			{
				$tag_table = $this->_helper->api()->getDbtable('tags', 'wall');
				$tag = $tag_table->createRow();
				$tag->user_id = $viewer->user_id;
				$tag->action_id = $action->action_id;
				$tag->taggeduser_id = $viewer->user_id;
				;
				$tag->save();
				foreach ($friendusers as $frienduser)
				{
					$tag = $tag_table->createRow();
					$tag->user_id = $viewer->user_id;
					$tag->action_id = $action->action_id;
					$tag->taggeduser_id = $frienduser;
					$tag->save();
					$taguser = $this->_helper->api()->user()->getUser($frienduser);
					$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
					$notifyApi->addNotification($taguser, $viewer, $action, 'tag');
				}
			}
			$db->commit();
		} // end "try"
		catch (Exception $e)
		{
			$db->rollBack();
			throw $e; // This should be caught by error handler
		}

		// If we're here, we're done
		$this->view->status = true;
		$this->view->message = Zend_Registry::get('Zend_Translate')->_('Success!');

		// Redirect if in normal context
//        if (null === $this->_helper->contextSwitch->getCurrentContext())
//        {
//            $return_url = $form->getValue('return_url', false);
//            if ($return_url)
//            {
//                return $this->_helper->redirector->gotoUrl($return_url, array('prependBase' => false));
//            }
//        }
		//get last id

		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(TRUE);
		$actionTable = Engine_Api::_()->getDbtable('actions', 'activity');
		$Name = $actionTable->info('name');
		$select = $actionTable->select()->from($Name, array('action_id'))->order('action_id DESC')->limit(1);
		$result = $actionTable->fetchRow($select);
		echo $result->action_id;
	}

	public function shareAction()
	{
		if (!$this->_helper->requireUser()->isValid())
			return;

		$type = $this->_getParam('type');
		$id = $this->_getParam('id');

		$viewer = Engine_Api::_()->user()->getViewer();
		$this->view->attachment = $attachment = Engine_Api::_()->getItem($type, $id);
		$form = new Wall_Form_Share();
		if ($this->_getParam('come_from_commentbox') == 'true')
		{
			$form->removeElement('wall');
		}
		$this->view->form = $form;

		if (!$attachment)
		{
			// tell smoothbox to close
			$this->view->status = true;
			$this->view->message = Zend_Registry::get('Zend_Translate')->_('You cannot share this item because it has been removed.');
			$this->view->smoothboxClose = true;
			return $this->render('deletedItem');
		}

		// hide facebook option if not logged in, or logged into wrong FB account
		if (true)
		{
			//$facebook = User_Model_DbTable_Facebook::getFBInstance();
			$facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
			if (!( 'publish' == Engine_Api::_()->getApi('settings', 'core')->core_facebook_enable &&
					$facebookTable->getApi() &&
					$facebookTable->isConnected()))
			{
				$form->removeElement('post_to_facebook');
			}
			else
			{
				try
				{
					$facebookApi = $facebook = $facebookTable->getApi();
					$fb_uid = $facebookTable->find($viewer->getIdentity())->current();

					if ($fb_uid && $fb_uid->facebook_uid)
						$fb_uid = $fb_uid->facebook_uid;
					else
						$fb_uid = null;

					if (!$fb_uid || $fb_uid != $facebookApi->getUser())
					{
						throw new Exception('User logged into a Facebook account other than the attached account.');
					}
				}
				catch (Exception $e)
				{
					$form->removeElement('post_to_facebook');
				}
			}
		}

		if (!$this->getRequest()->isPost())
		{
			return;
		}

		if (!$form->isValid($this->getRequest()->getPost()))
		{
			if ($form->getValue('shareto') == 'friend')
			{
				return;
			}
		}

		// Process

		$db = Engine_Api::_()->getDbtable('actions', 'activity')->getAdapter();
		$api = $this->_helper->api()->getDbtable('actions', 'activity');

		$db->beginTransaction();
		try
		{
			// Get body
			$body = $form->getValue('body');
			$shareto = $form->getValue('shareto');

			if ($shareto == 'me')
			{
				// Add activity
				$action = $api->addActivity($viewer, $viewer, 'post_self', $body);
				$api->attachActivity($action, $attachment);

				//Set privacy
				$privacy_set = $this->getRequest()->getParam('privacy');
				if ($privacy_set)
				{
					$privacy = $this->_helper->api()->getDbtable('privacies', 'wall');
					$row = $privacy->createRow();
					$row->action_id = $action->action_id;
					$row->user_id = $viewer->user_id;
					$row->privacy = $privacy_set;
					$row->save();
				}

				// Publish to facebook, if checked & enabled
				if ($this->_getParam('post_to_facebook', false) &&
						'publish' == Engine_Api::_()->getApi('settings', 'core')->core_facebook_enable)
				{
					try
					{

						$facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
						$facebookApi = $facebook = $facebookTable->getApi();
						$fb_uid = $facebookTable->find($viewer->getIdentity())->current();

						if ($fb_uid &&
								$fb_uid->facebook_uid &&
								$facebookApi &&
								$facebookApi->getUser() &&
								$facebookApi->getUser() == $fb_uid->facebook_uid)
						{
							$url = 'http://' . $_SERVER['HTTP_HOST'] . $this->getFrontController()->getBaseUrl();
							$name = 'Activity Feed';
							$desc = '';
							$picUrl = $viewer->getPhotoUrl('thumb.icon');
							if ($attachment)
							{
								$url = $attachment->getHref();
								$desc = $attachment->getDescription();
								$name = $attachment->getTitle();
								if (empty($name))
								{
									$name = ucwords($attachment->getShortType());
								}
								$tmpPicUrl = $attachment->getPhotoUrl();
								if ($tmpPicUrl)
								{
									$picUrl = $tmpPicUrl;
								}
								// prevents OAuthException: (#100) FBCDN image is not allowed in stream
								if (preg_match('/fbcdn.net$/i', parse_url($picUrl, PHP_URL_HOST)))
								{
									$picUrl = $viewer->getPhotoUrl('thumb.icon');
								}
							}

							// Check stuff
							if (false === stripos($url, 'http://'))
							{
								$url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
							}
							if (false === stripos($picUrl, 'http://'))
							{
								$picUrl = 'http://' . $_SERVER['HTTP_HOST'] . $picUrl;
							}

							// include the site name with the post:
							$name = Engine_Api::_()->getApi('settings', 'core')->core_general_site_title
									. ": $name";

							$fb_data = array(
								'message' => html_entity_decode($form->getValue('body')),
								'link' => $url,
								'name' => $name,
								'description' => $desc,
							);

							if ($picUrl)
							{
								$fb_data = array_merge($fb_data, array('picture' => $picUrl));
							}

							$res = $facebook->api('/me/feed', 'POST', $fb_data);
						}
					}
					catch (Exception $e)
					{
						// Silence
					}
				} // end Facebook
				// Publish to twitter, if checked & enabled
				if ($this->_getParam('post_to_twitter', false) &&
						'publish' == Engine_Api::_()->getApi('settings', 'core')->core_twitter_enable)
				{
					try
					{
						$twitterTable = Engine_Api::_()->getDbtable('twitter', 'user');
						if ($twitterTable->isConnected())
						{

							// Get attachment info
							$title = $attachment->getTitle();
							$url = $attachment->getHref();
							$picUrl = $attachment->getPhotoUrl();

							// Check stuff
							if ($url && false === stripos($url, 'http://'))
							{
								$url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
							}
							if ($picUrl && false === stripos($picUrl, 'http://'))
							{
								$picUrl = 'http://' . $_SERVER['HTTP_HOST'] . $picUrl;
							}

							// Try to keep full message
							// @todo url shortener?
							$message = html_entity_decode($form->getValue('body'));
							if (strlen($message) + strlen($title) + strlen($url) + strlen($picUrl) + 9 <= 140)
							{
								if ($title)
								{
									$message .= ' - ' . $title;
								}
								if ($url)
								{
									$message .= ' - ' . $url;
								}
								if ($picUrl)
								{
									$message .= ' - ' . $picUrl;
								}
							}
							else if (strlen($message) + strlen($title) + strlen($url) + 6 <= 140)
							{
								if ($title)
								{
									$message .= ' - ' . $title;
								}
								if ($url)
								{
									$message .= ' - ' . $url;
								}
							}
							else
							{
								if (strlen($title) > 24)
								{
									$title = Engine_String::substr($title, 0, 21) . '...';
								}
								// Sigh truncate I guess
								if (strlen($message) + strlen($title) + strlen($url) + 9 > 140)
								{
									$message = Engine_String::substr($message, 0, 140 - (strlen($title) + strlen($url) + 9)) - 3 . '...';
								}
								if ($title)
								{
									$message .= ' - ' . $title;
								}
								if ($url)
								{
									$message .= ' - ' . $url;
								}
							}

							$twitter = $twitterTable->getApi();
							$twitter->statuses->update($message);
						}
					}
					catch (Exception $e)
					{
						// Silence
					}
				}//End Twitter
			}

			if ($shareto == 'friend')
			{
				$type = 'post';
				$toValues = $form->getValue('toValues');

				$recipients = preg_split('/[,. ]+/', $toValues);
				// clean the recipients for repeating ids
				// this can happen if recipient is selected and then a friend list is selected
				$recipients = array_unique($recipients);
				// Slice down to 10
				//$recipients = array_slice($recipients, 0, $maxRecipients);
				$recipientsUsers = Engine_Api::_()->getItemMulti('user', $recipients);

				foreach ($recipientsUsers as $user)
				{
					//Add notification
					if (!$viewer->isSelf($user) && $user instanceof User_Model_User)
					{
						$notificationType = 'post_' . $user->getType();
						Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($user, $viewer, $user, $notificationType, array(
							'url1' => $user->getHref(),
						));
					}

					//Add activity
					$action = $api->addActivity($viewer, $user, 'post', $body);
					$api->attachActivity($action, $attachment);
				}
			}

			$db->commit();
		}
		catch (Exception $e)
		{
			$db->rollBack();
			throw $e; // This should be caught by error handler
		}

		// If we're here, we're done
		$this->view->status = true;
		$this->view->message = Zend_Registry::get('Zend_Translate')->_('Success!');

		// Redirect if in normal context
		if (null === $this->_helper->contextSwitch->getCurrentContext())
		{
			$return_url = $form->getValue('return_url', false);
			if (!$return_url)
			{
				$return_url = $this->view->url(array(), 'default', true);
			}
			return $this->_helper->redirector->gotoUrl($return_url, array('prependBase' => false));
		}
		else if ('smoothbox' === $this->_helper->contextSwitch->getCurrentContext())
		{
			$this->_forward('success', 'utility', 'core', array(
				'smoothboxClose' => 10,
				'parentRefresh' => 10,
				'messages' => array('')
			));
		}
	}

	function deleteAction()
	{
		$viewer = Engine_Api::_()->user()->getViewer();
		$activity_moderate = Engine_Api::_()->getDbtable('permissions', 'authorization')->getAllowed('user', $viewer->level_id, 'activity');

		if (!$this->_helper->requireUser()->isValid())
			return;

		// Identify if it's an action_id or comment_id being deleted
		$this->view->comment_id = $comment_id = $this->_getParam('comment_id', null);
		$this->view->action_id = $action_id = $this->_getParam('action_id', null);

		$action = Engine_Api::_()->getDbtable('actions', 'activity')->getActionById($action_id);
		if (!$action)
		{
			// tell smoothbox to close
			$this->view->status = true;
			$this->view->message = Zend_Registry::get('Zend_Translate')->_('You cannot share this item because it has been removed.');
			$this->view->smoothboxClose = true;
			return $this->render('deletedItem');
		}

		// Send to view script if not POST
		if (!$this->getRequest()->isPost())
			return;


		// Both the author and the person being written about get to delete the action_id
		if (!$comment_id && (
				$activity_moderate ||
				('user' == $action->subject_type && $viewer->getIdentity() == $action->subject_id) || // owner of profile being commented on
				('user' == $action->object_type && $viewer->getIdentity() == $action->object_id)))
		{   // commenter
			// Delete action item and all comments/likes
			$db = Engine_Api::_()->getDbtable('actions', 'activity')->getAdapter();
			$db->beginTransaction();
			try
			{
				$action->deleteItem();

				$row = Engine_Api::_()->getDbtable('privacies', 'wall')->fetchRow("action_id = $action_id");
				if (isset($row->privacy_id))
				{
					$row->delete();
				}
				$db->commit();

				// tell smoothbox to close
				$this->view->status = true;
				$this->view->message = Zend_Registry::get('Zend_Translate')->_('This activity item has been removed.');
				$this->view->smoothboxClose = true;
				return $this->render('deletedItem');
			}
			catch (Exception $e)
			{
				$db->rollback();
				$this->view->status = false;
			}
		}
		elseif ($comment_id)
		{
			$comment = $action->comments()->getComment($comment_id);
			// allow delete if profile/entry owner
			$db = Engine_Api::_()->getDbtable('comments', 'activity')->getAdapter();
			$db->beginTransaction();
			if ($activity_moderate ||
					('user' == $comment->poster_type && $viewer->getIdentity() == $comment->poster_id) ||
					('user' == $action->object_type && $viewer->getIdentity() == $action->object_id))
			{
				try
				{
					$action->comments()->removeComment($comment_id);
					$db->commit();
					$this->view->message = Zend_Registry::get('Zend_Translate')->_('Comment has been deleted');
					return $this->render('deletedComment');
				}
				catch (Exception $e)
				{
					$db->rollback();
					$this->view->status = false;
				}
			}
			else
			{
				$this->view->message = Zend_Registry::get('Zend_Translate')->_('You do not have the privilege to delete this comment');
				return $this->render('deletedComment');
			}
		}
		else
		{
			// neither the item owner, nor the item subject.  Denied!
			$this->_forward('requireauth', 'error', 'core');
		}
	}

	public function viewcommentAction()
	{
		// Collect params
		$action_id = $this->_getParam('action_id');
		$viewer = $this->_helper->api()->user()->getViewer();

		$action = $this->_helper->api()->getDbtable('actions', 'activity')->getActionById($action_id);
		$form = $this->view->form = new Activity_Form_Comment();
		$form->setActionIdentity($action_id);


		// Redirect if not json context
		if (null === $this->_getParam('format', null))
		{
			$this->_helper->redirector->gotoRoute(array(), 'core_home');
		}
		else if ('json' === $this->_getParam('format', null))
		{
			$this->view->body = $this->view->activity($action, array('viewAllComments' => true, 'noList' => $this->_getParam('nolist', false)));
		}
	}

	public function commentAction()
	{
		// Make sure user exists
		if (!$this->_helper->requireUser()->isValid())
			return;

		// Make form

		$this->view->form = $form = new Wall_Form_Comment();
		$this->view->form->setID($this->_getParam('action_id'));

		// Not post
		if (!$this->getRequest()->isPost())
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Not a post');
			return;
		}

		// Not valid
		if (!$form->isValid($this->getRequest()->getPost()))
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid data');
			return;
		}

		// Start transaction
		$db = $this->_helper->api()->getDbtable('actions', 'activity')->getAdapter();
		$db->beginTransaction();

		try
		{
			$viewer = $this->_helper->api()->user()->getViewer();
			$action_id = $this->view->action_id = $this->_getParam('action_id', $this->_getParam('action', null));
			$action = $this->_helper->api()->getDbtable('actions', 'activity')->getActionById($action_id);
			$actionOwner = Engine_Api::_()->getItemByGuid($action->subject_type . "_" . $action->subject_id);
			$body = $form->getValue('body');

			/* Emotions */
			$body = str_replace('src="../externals/tinymce/plugins/emotions/img/', 'src="externals/tinymce/plugins/emotions/img/', $body);

			// Check authorization
			if (!Engine_Api::_()->authorization()->isAllowed($action->getObject(), null, 'comment'))
				throw new Engine_Exception('This user is not allowed to comment on this item.');

			// Add the comment
			$action->comments()->addComment($viewer, $body);

			// Notifications
			$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');

			// Add notification for owner of activity (if user and not viewer)
			if ($action->subject_type == 'user' && $action->subject_id != $viewer->getIdentity())
			{
				$notifyApi->addNotification($actionOwner, $viewer, $action, 'commented', array(
					'label' => 'post'
				));
			}

			// Add a notification for all users that commented or like except the viewer and poster
			// @todo we should probably limit this
			foreach ($action->comments()->getAllCommentsUsers() as $notifyUser)
			{
				if ($notifyUser->getIdentity() != $viewer->getIdentity() && $notifyUser->getIdentity() != $actionOwner->getIdentity())
				{
					$notifyApi->addNotification($notifyUser, $viewer, $action, 'commented_commented', array(
						'label' => 'post'
					));
				}
			}

			// Add a notification for all users that commented or like except the viewer and poster
			// @todo we should probably limit this
			foreach ($action->likes()->getAllLikesUsers() as $notifyUser)
			{
				if ($notifyUser->getIdentity() != $viewer->getIdentity() && $notifyUser->getIdentity() != $actionOwner->getIdentity())
				{
					$notifyApi->addNotification($notifyUser, $viewer, $action, 'liked_commented', array(
						'label' => 'post'
					));
				}
			}

			$db->commit();
		}
		catch (Exception $e)
		{
			$db->rollBack();
			throw $e;
		}

		// Assign message for json
		$this->view->status = true;
		$this->view->message = 'Comment posted';

		// Redirect if not json
		if (null === $this->_getParam('format', null))
		{
			$this->_redirect($form->return_url->getValue(), array('prependBase' => false));
		}
		else if ('json' === $this->_getParam('format', null))
		{
			$this->view->body = $this->view->wall($action, array('noList' => true));
		}
	}

	public function uploadphotoAction()
	{
		$this->_helper->layout->setLayout('admin-simple');


		if (isset($_GET['ul']) || isset($_FILES['Filedata']))
			return $this->_forward('uploadimage', null, null, array('format' => 'json'));

		$viewer = Engine_Api::_()->user()->getViewer();

		$this->view->form = $form = new Wall_Form_Uploadphoto();
		$form->file->setAttrib('data', array('user_id' => $viewer->getIdentity()));

		if (!$this->getRequest()->isPost())
		{
			return;
		}

		if (!$form->isValid($this->getRequest()->getPost()))
		{
			return;
		}

		$values = $form->getValues();
		$params = array(
			'owner_type' => 'user',
			'owner_id' => $viewer->getIdentity(),
		);
	}

	public function uploadimageAction()
	{


		if (!$this->getRequest()->isPost())
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
			return;
		}

		$values = $this->getRequest()->getPost();
		if (empty($values['Filename']))
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('No file');
			return;
		}

		if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name']))
		{
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Upload');
			return;
		}

		$viewer = Engine_Api::_()->user()->getViewer();

		$params = array(
			'owner_type' => 'user',
			'owner_id' => $viewer->getIdentity(),
		);
		$parameters = Wall_Api_Advcomment::createPhoto($params, $_FILES['Filedata']);

		$photo_id = $parameters['photo_id'];

		$this->view->status = true;
		$this->view->name = $_FILES['Filedata']['name'];
		$this->view->photo_id = $photo_id;

		$storage_table = Engine_Api::_()->getDbTable('files', 'storage');

		$select = $storage_table->select()->where('file_id = ?', $photo_id);
		$rows = $storage_table->fetchAll($select);

		$result_link = (string) $rows[0]['storage_path'];

		if (isset($rows))
		{
			if ($result_link[0] == '<')
			{
				$result_link = str_replace('"></a>', '', $result_link);
				$result_link = str_replace('<a  href="', '', $result_link);
				//$result_link = 'http://' . $result_link;
				//$result_link = $result_link;
			}
		}
		else
		{
			$result_link = 0;
		}

		$this->view->result_link = $result_link;
	}

	public function testAction()
	{
		$this->_helper->layout->disableLayout();
		$viewer = Engine_Api::_()->user()->getViewer();
		$friendUsers = Engine_Api::_()->wall()->getViewerFriends($viewer);
		echo Zend_Json::encode($friendUsers);
	}

	public function getUserInfoAction()
	{
		$this->_helper->layout->disableLayout();

		$id = $this->_getParam('id');
		$name = $this->_getParam('name');
		$type = $this->_getParam('type');

		$error = '';

		if ($id && $type)
		{
			$this->view->type = $type;
			if ($type == 'user')
			{
				$username_or_user_id = ($id == 'undefined') ? $name : $id;
				$this->view->user = $user = Engine_Api::_()->user()->getUser($username_or_user_id);
				$this->view->idMessage = $user->getIdentity();
				$this->view->friends = Engine_Api::_()->wall()->getViewerFriends($user);
			}
			if ($type == 'group')
			{
				$this->view->group = $group = Engine_Api::_()->getItem('group', $id);
				$users_table = Engine_Api::_()->getDbtable('users', 'user');
				$users_table->getAdapter();

				$select = $group->membership()->getMembersObjectSelect();
				$this->view->groupMembers = $users_table->fetchAll($select);

				$viewer = Engine_Api::_()->user()->getViewer();
				$group_row = $group->membership()->getRow($viewer);

				if (null === $group_row)
				{
					if ($group->membership()->isResourceApprovalRequired())
					{
						$this->view->groupAction = 'request';
					}
					else
					{
						$this->view->groupAction = 'join';
					}
				}
				else if ($group_row->active)
				{
					if (!$group->isOwner($viewer))
					{
						$this->view->groupAction = 'leave';
					}
					else
					{
						$this->view->groupAction = 'delete';
					}
				}
				else if (!$group_row->resource_approved && $group_row->user_approved)
				{
					$this->view->groupAction = 'cancel';
				}
				else if (!$row->user_approved && $row->resource_approved)
				{
					$this->view->groupAction = 'accept-or-reject';
				}
			}
		}
		else
		{
			$error = 'An error occurs';
		}
		$this->view->error = $error;
	}

	protected function _shareToFacebookTwitter($user, $attachment)
	{
		
	}

}
